package com.ftg.supermarket.service;

import com.ftg.supermarket.comm.JwtComm;
import com.ftg.supermarket.comm.Md5Me;
import com.ftg.supermarket.comm.ToPage;
import com.ftg.supermarket.domain.UserDomain;
import com.ftg.supermarket.mapper.UserMapper;
import com.ftg.supermarket.util.MapperUtil;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户业务处理
 * {
 * name:kjx,
 * age:39,
 * tel:15326619037
 * }
 *
 * @author 布衣
 */
public class UserService {

    UserMapper userMapper;
    MapperUtil mapperUtil = new MapperUtil("config/configuration.xml");

    public UserService() throws IOException {
        userMapper = mapperUtil.getMapper(UserMapper.class);
    }

    public ToPage<Object> login(String username, String password) {

        UserDomain userDomain = userMapper.checkUserNameWithPassWord(username);
        if (userDomain == null) {
            return ToPage.error("用户名错误");
        }
        if (!userDomain.getPassword().equals(Md5Me.getMD5(password))) {
            return ToPage.error("密码错误");
        }
        //加一点业务和新的技术点
        Map<String, Object> map = new HashMap<>();
        map.put("username", username);
        map.put("userid", userDomain.getId());
        String token = JwtComm.createToken(map);
        return ToPage.success("登录成功", token);
    }

    /**
     * 注册用户
     * 调用添加
     */
    public ToPage<Object> register(String username, String password) {
        //判断是否重复
        try {
            if (null == userMapper.findOneByUsername(username)) {
                password = Md5Me.getMD5(password);
                int num = userMapper.saveUser(username, password);
                mapperUtil.myCommit();
                return num > 0 ? ToPage.success() : ToPage.error();
            }
        } catch (Exception e) {
            mapperUtil.myRollback();
        } finally {
            mapperUtil.myClose();
        }
        return ToPage.error("对不起，当前帐号已注册！！！");
    }


}
